package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.result.course.ChapterVo;
import com.atguigu.eduservice.entity.result.course.CoursePublishVo;
import com.atguigu.eduservice.entity.result.course.VideoVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CourseQuery;
import com.atguigu.eduservice.entity.vo.front.CourseQueryVo;
import com.atguigu.eduservice.entity.result.course.CourseWebVo;
import com.atguigu.eduservice.mapper.EduCourseMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduCourseService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author 老王
 * @since 2020-05-20
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {
    @Autowired
    private EduCourseDescriptionService courseDescriptionService;//课程简介service
    @Autowired
    private EduChapterService chapterService;//章节service
    @Autowired
    private EduVideoService videoService;//小节service

    //条件分页查询课程列表
    @Override
    public void pageQuery(Page<EduCourse> pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");

        if (courseQuery == null){
            baseMapper.selectPage(pageParam, queryWrapper);
            return;
        }

        String title = courseQuery.getTitle();
        String teacherId = courseQuery.getTeacherId();
        String subjectParentId = courseQuery.getSubjectParentId();
        String subjectId = courseQuery.getSubjectId();

        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", title);
        }

        if (!StringUtils.isEmpty(teacherId) ) {
            queryWrapper.eq("teacher_id", teacherId);
        }

        if (!StringUtils.isEmpty(subjectParentId)) {
            queryWrapper.ge("subject_parent_id", subjectParentId);
        }

        if (!StringUtils.isEmpty(subjectId)) {
            queryWrapper.ge("subject_id", subjectId);
        }
        baseMapper.selectPage(pageParam, queryWrapper);
    }

    //添加课程信息
    @Override
    public String addCourseInfo(CourseInfoVo courseInfoVo) {
        //1.先添加课程
        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, course);
        if(!this.save(course)){
            throw new GuliException(20001,"添加课程信息失败");
        }

        //获取id赋值给课程描述信息，因为是1对1关系，所以id相同
        String courseId=course.getId();
        System.out.println("课程id:"+courseId);

        //2.再添加课程描述信息
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseId);
        description.setDescription(courseInfoVo.getDescription());
        if (!courseDescriptionService.save(description)){
            throw new GuliException(20001,"添加课程信息失败");
        }
        return courseId;
    }

    //根据id查询课程章节和小节
    @Override
    public List<ChapterVo> getChapterOrVideo(String courseId) {
        //1.先查出所有章节封装到List里面
        QueryWrapper<EduChapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id", courseId);
        List<EduChapter> chapterList = chapterService.list(chapterWrapper);

        //2.查出课程所有小节
        QueryWrapper<EduVideo> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        List<EduVideo> videoList = videoService.list(videoWrapper);

        //3.结果集
        ArrayList<ChapterVo> list = new ArrayList<>();
        //3.遍历所有章节和小节，把小节封装进去对应的章节
        for (int i = 0; i < chapterList.size(); i++) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapterList.get(i), chapterVo);//拷贝属性

            for (int j = 0; j < videoList.size(); j++) {
                if (chapterVo.getId().equals(videoList.get(j).getChapterId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(videoList.get(j), videoVo);//拷贝属性
                    //小节封装进去
                    chapterVo.getChildren().add(videoVo);
                }
            }
            list.add(chapterVo);
        }
        //4.list
        return list;
    }

    //根据id查询课程（包含课程和描述表）
    @Override
    public CourseInfoVo getCourseInfoVoById(String courseId) {
        EduCourse course = this.getById(courseId);
        //封装进courseInfoVo
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoVo);

        //查描述
        EduCourseDescription description = courseDescriptionService.getById(courseId);
        BeanUtils.copyProperties(description, courseInfoVo);
        return courseInfoVo;
    }

    //修改课程基础信息
    @Override
    public void updateCourse(CourseInfoVo courseInfoVo) {
        //修改课程信息
        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, course);
        if(!this.updateById(course)){
            throw new GuliException(20001,"修改课程信息失败");
        }

        //修改对应的描述表信息
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        if (!courseDescriptionService.updateById(description)){
            throw new GuliException(20001,"修改课程信息失败");
        }
    }

    //根据id查课程信息（最终确认回显信息）
    @Override
    public CoursePublishVo getCoursePublishVoById(String id) {
        return baseMapper.getCoursePublishVoById(id);
    }

    //根据id发布课程
    @Override
    public boolean publishCourseById(String id) {
        EduCourse course = new EduCourse();
        course.setId(id);
        course.setStatus(EduCourse.COURSE_NORMAL);
        Integer count = baseMapper.updateById(course);
        return null != count && count > 0;
    }

    @Override
    public boolean removeCourseById(String id) {
        //根据id删除所有视频
        videoService.removeByCourseId(id);

        //根据id删除所有章节
        chapterService.removeByCourseId(id);

        Integer result = baseMapper.deleteById(id);
        return null != result && result > 0;
    }

    //根据讲师id查询课程列表
    @Override
    public List<EduCourse> selectByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<EduCourse>();

        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");

        List<EduCourse> courses = baseMapper.selectList(queryWrapper);
        return courses;
    }

    //前台条件查询课程列表
    @Override
    public Map<String, Object> pageListWeb(Page<EduCourse> pageParam, CourseQueryVo courseQuery) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Autowired
    private EduCourseMapper courseMapper;
    @Override
    public CourseWebVo selectInfoWebById(String id) {
        this.updatePageViewCount(id);
        return courseMapper.selectInfoWebById(id);
    }

    @Override
    public void updatePageViewCount(String id) {
        EduCourse course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }
}
